<!--
 * @Description: 渠道码
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2022-09-02 09:21:18
 * @LastEditTime: 2023-08-07 16:05:25
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
  <div class="lb-channel-qr">
    <top-nav />
    <div class="page-main">
      <el-row class="page-top-operate">
        <lb-button
          size="medium"
          type="primary"
          icon="el-icon-plus"
          @click="toShowDialog('sub')"
          v-hasPermi="`${$route.name}-add`"
          >{{ $t('menu.ChannelQrAdd') }}</lb-button
        >
      </el-row>
      <el-row class="page-search-form">
        <el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm.list"
          ref="listForm"
        >
          <el-form-item label="编码" prop="code">
            <el-input
              v-model="searchForm.list.code"
              placeholder="请输入编码"
            ></el-input>
          </el-form-item>
          <el-form-item label="渠道商" prop="channel_name">
            <el-input
              v-model="searchForm.list.channel_name"
              placeholder="请输入渠道商姓名"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1, 'list')"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('list')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <el-table
        v-loading="loading.list"
        ref="multipleTable"
        :data="tableData.list"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
        @selection-change="handleMulSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="selectable"
          v-if="
            $route.meta.pagePermission[0].auth.includes('batchDownloadQr') ||
            $route.meta.pagePermission[0].auth.includes('batchDelete') ||
            $route.meta.pagePermission[0].auth.includes('batchBindChannel')
          "
        ></el-table-column>
        <el-table-column prop="title" label="渠道码名称" width="150" fixed>
        </el-table-column>
        <el-table-column prop="code" label="编码" min-width="150">
        </el-table-column>
        <el-table-column prop="cate_name" label="所属类目" min-width="150">
        </el-table-column>
        <el-table-column prop="title" label="绑定状态" min-width="120">
          <template slot-scope="scope">
            {{
              scope.row.channel_id && scope.row.channel_name
                ? '已绑定'
                : '未绑定'
            }}
          </template>
        </el-table-column>
        <el-table-column prop="nickName" label="绑定人员" min-width="120">
        </el-table-column>
        <el-table-column prop="channel_name" label="渠道商姓名" min-width="120">
        </el-table-column>
        <el-table-column prop="balance" label="渠道分成" min-width="120">
          <template slot-scope="scope"> {{ scope.row.balance }}% </template>
        </el-table-column>
        <el-table-column prop="qr" label="渠道码" min-width="120">
          <template slot-scope="scope">
            <div class="flex-between">
              <lb-image
                :src="scope.row.qr"
                :isLook="true"
                :title="scope.row.code"
                width="480px"
              />
              <div></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" min-width="120">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="160">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="toShowDialog('sub', scope.row)"
                v-hasPermi="`${$route.name}-edit`"
                >{{ $t('action.edit') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="confirmDel([scope.row.id], scope.row.code)"
                v-hasPermi="`${$route.name}-delete`"
                >{{ $t('action.delete') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="warning"
                @click="toDownload(scope.row.id)"
                v-hasPermi="`${$route.name}-downloadQr`"
                >{{ $t('action.downloadQr') }}</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <lb-page
        :batch="
          $route.meta.pagePermission[0].auth.includes('batchDownloadQr') ||
          $route.meta.pagePermission[0].auth.includes('batchDelete') ||
          $route.meta.pagePermission[0].auth.includes('batchBindChannel')
        "
        :selected="multipleSelection.length"
        :page="searchForm.list.page"
        :pageSize="searchForm.list.limit"
        :sizes="[5, 10, 20, 50, 80, 100]"
        :total="total.list"
        @handleSizeChange="handleSizeChange($event, 'list')"
        @handleCurrentChange="handleCurrentChange($event, 'list')"
      >
        <lb-button
          size="mini"
          type="warning"
          @click="toBatch(1)"
          v-hasPermi="`${$route.name}-batchDownloadQr`"
          >{{ $t('action.batchDownloadQr') }}</lb-button
        >
        <lb-button
          size="mini"
          type="danger"
          @click="toBatch(2)"
          v-hasPermi="`${$route.name}-batchDelete`"
          >{{ $t('action.batchDelete') }}</lb-button
        >
        <lb-button
          size="mini"
          type="success"
          @click="toBatch(3)"
          v-hasPermi="`${$route.name}-batchBindChannel`"
          >{{ $t('action.batchBindChannel') }}</lb-button
        >
      </lb-page>

      <el-dialog
        :title="$t(subForm.id ? 'menu.ChannelQrEdit' : 'menu.ChannelQrAdd')"
        :visible.sync="showDialog.sub"
        width="550px"
        center
      >
        <el-form
          :model="subForm"
          ref="subForm"
          :rules="subFormRules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="渠道码名称" prop="title">
            <el-input
              v-model="subForm.title"
              maxlength="10"
              show-word-limit
              placeholder="请输入渠道码名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="渠道类目" prop="cate_id">
            <el-select
              v-model="subForm.cate_id"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in base_channel"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="渠道分成" prop="balance">
            <el-input v-model="subForm.balance" placeholder="请输入渠道分成">
              <template slot="append">%</template>
            </el-input>
            <lb-tool-tips
              >每个渠道码可获得的佣金分成，用户通过该渠道码扫码下单后，能记录到佣金</lb-tool-tips
            >
          </el-form-item>
          <el-form-item label="绑定人员" prop="user_id">
            <el-tag
              class="cursor-pointer"
              @close="toClearUser"
              :closable="subForm.user_id"
              :type="subForm.user_id ? 'primary' : 'danger'"
              @click="toShowDialog('user')"
              >{{ subForm.user_id ? subForm.nickName : '选择绑定人员' }}</el-tag
            >
          </el-form-item>
          <el-form-item label="渠道码数量" prop="num" v-if="!subForm.id">
            <el-input-number
              class="lb-input-number"
              :min="1"
              :max="20"
              :precision="0"
              :controls="false"
              v-model="subForm.num"
              placeholder="请输入渠道码数量"
            ></el-input-number>
            <lb-tool-tips>一次性最多只能20个</lb-tool-tips>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.sub = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('sub')"
            v-loading="lockTap"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        :title="$t('action.batchBindChannel')"
        :visible.sync="showDialog.bind"
        width="550px"
        center
      >
        <el-form
          :model="bindForm"
          ref="bindForm"
          :rules="bindFormRules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="绑定人员" prop="user_id">
            <el-tag
              class="cursor-pointer"
              :type="bindForm.user_id ? 'primary' : 'danger'"
              @click="toShowDialog('user')"
              >{{
                bindForm.user_id ? bindForm.nickName : '选择绑定人员'
              }}</el-tag
            >
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.bind = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('bind')"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        title="选择绑定人员"
        :visible.sync="showDialog.user"
        width="800px"
        center
      >
        <lb-tips v-if="routesItem.userInfo.is_admin === 0"
          >请输入微信昵称/手机号/渠道商姓名/渠道商手机号后点击查询数据</lb-tips
        >
        <el-form
          :inline="true"
          :model="searchForm.user"
          ref="userForm"
          label-width="70px"
          class="dialog-form"
        >
          <el-form-item label="输入查询" prop="name">
            <el-input
              v-model="searchForm.user.name"
              placeholder="请输入微信昵称/手机号/渠道商姓名/渠道商手机号"
              style="width: 380px"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1, 'user')"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('user')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
        <el-table
          v-loading="loading.user"
          :data="tableData.user"
          ref="singleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          highlight-current-row
          @current-change="handleSelectionChange"
        >
          <el-table-column prop="id" label="用户ID"></el-table-column>
          <el-table-column prop="avatarUrl" label="头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.avatarUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column prop="channel_name" label="渠道商姓名">
          </el-table-column>
          <el-table-column prop="mobile" label="渠道商手机号"></el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.user.page"
          :pageSize="searchForm.user.limit"
          :total="total.user"
          @handleSizeChange="handleSizeChange($event, 'user')"
          @handleCurrentChange="handleCurrentChange($event, 'user')"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.user = false">取 消</el-button>
          <el-button
            type="primary"
            @click="handleDialogConfirm"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { mapState } from 'vuex'
import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
export default {
  components: {},
  data () {
    let checkNum = (rule, value, callback) => {
      if (!this.subForm.id && !value) {
        callback(new Error('请输入渠道码数量'))
      } else {
        callback()
      }
    }
    return {
      loading: { list: false, user: false },
      base_type: [{ id: 0, title: '全部' }, { id: 1, title: '扫码次数最多' }, { id: 2, title: '订单量最多' }, { id: 3, title: '订单金额最多' }, { id: 4, title: '佣金最多' }],
      base_channel: [],
      searchForm: {
        list: {
          page: 1,
          limit: 10,
          code: '',
          channel_name: ''
        },
        user: {
          page: 1,
          limit: 10,
          name: ''
        }
      },
      tableData: { list: [], user: [] },
      total: { list: 0, user: 0 },
      currentRow: {},
      multipleSelection: [],
      showDialog: { sub: false, user: false, bind: false },
      subForm: {
        id: '',
        title: '',
        cate_id: '',
        balance: '',
        num: '',
        user_id: '',
        nickName: ''
      },
      subFormRules: {
        title: { required: true, validator: this.$reg.isNotNull, text: '渠道码名称', reg_type: 2, trigger: 'blur' },
        num: { required: true, validator: checkNum, trigger: 'blur' }
      },
      bindForm: {
        id: [],
        user_id: '',
        nickName: ''
      },
      bindFormRules: {
        // user_id: { required: true, type: 'number', message: '请选择绑定人员', trigger: ['blur', 'change'] }
      },
      lockTap: false
    }
  },
  async created () {
    await this.getBaseInfo()
    this.getTableDataList(1, 'list')
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    async getBaseInfo () {
      let { data } = await this.$api.channel.cateSelect()
      this.base_channel = data
    },
    resetForm (form) {
      let name = `${form}Form`
      this.$refs[name].resetFields()
      this.getTableDataList(1, form)
    },
    handleSizeChange (val, key) {
      this.searchForm[key].limit = val
      this.handleCurrentChange(1, key)
    },
    handleCurrentChange (val, key) {
      this.searchForm[key].page = val
      this.getTableDataList('', key)
    },
    async getTableDataList (flag, key) {
      if (flag) this.searchForm[key].page = 1
      this.tableData[key] = []
      this.loading[key] = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm[key]))
      let methodArr = {
        list: { methodKey: 'channel', methodModel: 'channelQr' },
        user: { methodKey: 'channel', methodModel: 'channelUserList' }
      }
      let { methodKey, methodModel } = methodArr[key]
      let { code, data } = await this.$api[methodKey][methodModel](searchForm)
      this.loading[key] = false
      if (code !== 200) return
      this.tableData[key] = data.data
      this.total[key] = data.total
    },
    handleMulSelectionChange (val) {
      this.multipleSelection = val
    },
    handleSelectionChange (val) {
      val = JSON.parse(JSON.stringify(val))
      let { id, nickName } = val
      val.nickName = nickName || `用户ID ${id}`
      this.currentRow = val
    },
    handleDialogConfirm () {
      if (this.currentRow === null || !this.currentRow.id) {
        this.$message.error(`请选择绑定人员`)
        return
      }
      let { id = 0, nickName = '' } = this.currentRow
      let key = this.showDialog.sub ? 'subForm' : 'bindForm'
      this[key].user_id = id
      this[key].nickName = nickName
      this.showDialog.user = false
    },
    async toBatch (key) {
      if (this.multipleSelection.length === 0) {
        this.$message.error(`请选择要操作的数据`)
        return
      }
      let id = this.multipleSelection.map(item => {
        return item.id
      })
      switch (key) {
        case 1:
          if (id.length === 1) {
            this.toDownload(id[0])
          } else {
            this.batchQrCodeZip(id)
          }
          break
        case 2:
          let title = ''
          this.multipleSelection.map((aitem, aindex) => {
            title += `${aindex === 0 ? `` : `、`}${aitem.code}`
          })
          this.confirmDel(id, title)
          break
        case 3:
          this.bindForm = {
            id,
            user_id: '',
            nickName: ''
          }
          this.showDialog.bind = true
          break
      }
    },
    async toDownload (id) {
      let { data } = await this.$api.channel.downloadQr({ id })
      let { qr_img: url, code: name } = data[0]
      FileSaver.saveAs(url, name)
      this.$message.success(`下载成功`)
    },
    async batchQrCodeZip (id) {
      let that = this
      let { data: datas } = await this.$api.channel.downloadQr({ id })
      let zip = new JSZip()
      const promises = []
      const cache = {}
      // 批量导出图片
      for (const item of datas) {
        const promise = that.getFile(item.qr_img).then((data) => {
          // 下载文件, 并存成ArrayBuffer对象
          zip.file(item.code + '.png', data, { binary: true }) // 逐个添加文件，需要加后缀".png"
          cache[item.code] = data
        })
        promises.push(promise)
      }
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: 'blob' }).then((content) => {
          // 生成二进制流
          FileSaver.saveAs(content, `渠道码 ${moment(new Date().getTime()).format('YYYY-MM-DD')}`) // 利用file-saver保存文件  自定义文件名
          that.$message.success(`下载成功`)
        })
      }).catch((res) => {
        that.$message.error('下载失败')
      })
    },
    getFile (url) {
      return new Promise((resolve, reject) => {
        axios({
          method: 'get',
          url,
          responseType: 'blob'
        }).then((response) => {
          resolve(response.data)
        }).catch((error) => {
          reject(error.toString())
        })
      })
    },
    /**
     * @method: 删除
     * @param {*} id
     */
    confirmDel (id, title) {
      const h = this.$createElement
      this.$confirm(h('p', null, [
        h('p', null, this.$t('tips.confirmDelete')),
        h('p', { style: 'font-size:13px;line-height:1.2;color: red' }, `删除后，渠道码“${title}”将作废！`)
      ]), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.updateItem(id)
      })
    },
    /**
     * @method: 上下架
     */
    async updateItem (id) {
      this.$api.channel.channelQrDel({ id }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('tips.successDel'))
          let total = id.length
          let key = 'list'
          this.searchForm[key].page = this.searchForm[key].page < Math.ceil((this.total[key] - total) / this.searchForm[key].limit) ? this.searchForm[key].page : Math.ceil((this.total[key] - total) / this.searchForm[key].limit)
          this.getTableDataList('', key)
        }
      })
    },
    async toShowDialog (key, item = {
      id: '',
      title: '',
      cate_id: '',
      balance: '',
      num: ''
    }) {
      if (key === 'sub') {
        for (let i in this.subForm) {
          this.subForm[i] = item[i]
        }
      } else {
        this.searchForm.user.name = ''
        await this.getTableDataList(1, 'user')
      }
      this.showDialog[key] = !this.showDialog[key]
    },
    toClearUser () {
      this.subForm.user_id = ''
      this.subForm.nickName = ''
    },
    async submitFormInfo (key) {
      let flag = true
      this.$refs[`${key}Form`].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this[`${key}Form`]))
        if (key === 'sub') {
          subForm.balance = subForm.balance || 0
          if (subForm.balance && !/^(?:0|[1-9][0-9]?|100)$/.test(subForm.balance)) {
            this.$message.error(`请输入正确的渠道分成，取值0至100`)
            return
          }
        }

        if (this.lockTap) return
        this.lockTap = true
        subForm.user_id = subForm.user_id || 0
        delete subForm.nickName
        if (key === 'sub' && !subForm.id) {
          this.$message({
            type: 'warning',
            message: `二维码正在生成中，请耐心等待！！！`,
            duration: 8000,
            showClose: true
          })
        }
        let methodModel = key === 'bind' ? 'bindChannel' : subForm.id ? 'channelQrUpdate' : 'channelQrAdd'
        try {
          let { code } = await this.$api.channel[methodModel](subForm)
          if (code !== 200) return
          this.lockTap = false
          this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
          this.showDialog[key] = false
          this.getTableDataList('', 'list')
        } catch (e) {
          this.lockTap = false
        }
      }
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-channel-qr {
  width: 100%;
  .page-main {
    width: 100%;
    .el-input,
    .el-select,
    .el-input-number {
      width: 200px;
    }
    .dialog-form {
      .el-input,
      .el-select,
      .el-input-number {
        width: 300px;
      }
    }
  }
}
</style>
